package com.imut.lagain.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.WechatNotification;
import com.imut.lagain.service.IWechatNotificationService;
import com.imut.lagain.util.JwtUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.*;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@RestController
@RequestMapping("/api/wechat-notifications")
@RequiredArgsConstructor
@Validated
public class WechatNotificationController {
    private static final Logger log = LoggerFactory.getLogger(WechatNotificationController.class);

    private final IWechatNotificationService wechatNotificationService;
    private final JwtUtil jwtUtil;

    @PostMapping
    public ResponseEntity<Map<String, Object>> createWechatNotification(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestBody @Valid CreateWechatNotificationRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            WechatNotification notification = new WechatNotification();
            notification.setUserId(userId);
            notification.setTemplateId(request.getTemplateId());
            notification.setEventType(request.getEventType());
            notification.setContent(request.getContent());
            notification.setSendStatus(request.getSendStatus());
            notification.setSendTime(request.getSendTime());

            boolean result = wechatNotificationService.save(notification);
            if (result) {
                response.put("success", true);
                response.put("message", "微信通知创建成功");
                response.put("data", notification);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "微信通知创建失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            log.error("创建微信通知失败", e);
            response.put("success", false);
            response.put("message", "创建微信通知失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getWechatNotification(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            WechatNotification notification = wechatNotificationService.getById(id);
            if (notification != null && notification.getUserId().equals(userId)) {
                response.put("success", true);
                response.put("data", notification);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "微信通知不存在或无权限访问");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            log.error("获取微信通知失败", e);
            response.put("success", false);
            response.put("message", "获取微信通知失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateWechatNotification(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id,
            @RequestBody @Valid UpdateWechatNotificationRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            WechatNotification notification = wechatNotificationService.getById(id);
            if (notification == null || !notification.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "微信通知不存在或无权限访问");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            notification.setTemplateId(request.getTemplateId());
            notification.setEventType(request.getEventType());
            notification.setContent(request.getContent());
            notification.setSendStatus(request.getSendStatus());
            notification.setSendTime(request.getSendTime());

            boolean result = wechatNotificationService.updateById(notification);
            if (result) {
                response.put("success", true);
                response.put("message", "微信通知更新成功");
                response.put("data", notification);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "微信通知更新失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            log.error("更新微信通知失败", e);
            response.put("success", false);
            response.put("message", "更新微信通知失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteWechatNotification(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            WechatNotification notification = wechatNotificationService.getById(id);
            if (notification == null || !notification.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "微信通知不存在或无权限访问");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            boolean result = wechatNotificationService.removeById(id);
            if (result) {
                response.put("success", true);
                response.put("message", "微信通知删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "微信通知删除失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            log.error("删除微信通知失败", e);
            response.put("success", false);
            response.put("message", "删除微信通知失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping
    public ResponseEntity<Map<String, Object>> getWechatNotifications(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "1") @Min(1) int page,
            @RequestParam(defaultValue = "10") @Min(1) @Max(100) int size,
            @RequestParam(required = false) String eventType,
            @RequestParam(required = false) String sendStatus) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            Page<WechatNotification> pageParam = new Page<>(page, size);
            IPage<WechatNotification> result = wechatNotificationService.getWechatNotificationsByUserId(userId, pageParam, eventType, sendStatus);

            response.put("success", true);
            response.put("data", result.getRecords());
            response.put("total", result.getTotal());
            response.put("page", result.getCurrent());
            response.put("size", result.getSize());
            response.put("pages", result.getPages());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取微信通知列表失败", e);
            response.put("success", false);
            response.put("message", "获取微信通知列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/pending")
    public ResponseEntity<Map<String, Object>> getPendingWechatNotifications(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @RequestParam(defaultValue = "10") @Min(1) @Max(100) int size) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            List<WechatNotification> notifications = wechatNotificationService.getPendingNotificationsByUserId(userId, size);
            response.put("success", true);
            response.put("data", notifications);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取待发送微信通知失败", e);
            response.put("success", false);
            response.put("message", "获取待发送微信通知失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updateSendStatus(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @PathVariable @Min(1) Long id,
            @RequestBody @Valid UpdateSendStatusRequest request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            WechatNotification notification = wechatNotificationService.getById(id);
            if (notification == null || !notification.getUserId().equals(userId)) {
                response.put("success", false);
                response.put("message", "微信通知不存在或无权限访问");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }

            notification.setSendStatus(request.getSendStatus());
            notification.setSendTime(request.getSendTime());

            boolean result = wechatNotificationService.updateById(notification);
            if (result) {
                response.put("success", true);
                response.put("message", "发送状态更新成功");
                response.put("data", notification);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "发送状态更新失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (Exception e) {
            log.error("更新发送状态失败", e);
            response.put("success", false);
            response.put("message", "更新发送状态失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getNotificationStats(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的token");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            Map<String, Object> stats = wechatNotificationService.getNotificationStatsByUserId(userId);
            response.put("success", true);
            response.put("data", stats);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取通知统计失败", e);
            response.put("success", false);
            response.put("message", "获取通知统计失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Data
    public static class CreateWechatNotificationRequest {
        @NotBlank(message = "模板ID不能为空")
        @Size(max = 100, message = "模板ID长度不能超过100个字符")
        private String templateId;

        @NotBlank(message = "事件类型不能为空")
        @Size(max = 50, message = "事件类型长度不能超过50个字符")
        private String eventType;

        @NotBlank(message = "通知内容不能为空")
        private String content;

        @Pattern(regexp = "^(PENDING|SENT|FAILED)$", message = "发送状态只能是PENDING、SENT或FAILED")
        private String sendStatus = "PENDING";

        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime sendTime;
        
        // Getter methods
        public String getTemplateId() {
            return templateId;
        }
        
        public String getEventType() {
            return eventType;
        }
        
        public String getContent() {
            return content;
        }
        
        public String getSendStatus() {
            return sendStatus;
        }
        
        public LocalDateTime getSendTime() {
            return sendTime;
        }
    }

    @Data
    public static class UpdateWechatNotificationRequest {
        @NotBlank(message = "模板ID不能为空")
        @Size(max = 100, message = "模板ID长度不能超过100个字符")
        private String templateId;

        @NotBlank(message = "事件类型不能为空")
        @Size(max = 50, message = "事件类型长度不能超过50个字符")
        private String eventType;

        @NotBlank(message = "通知内容不能为空")
        private String content;

        @Pattern(regexp = "^(PENDING|SENT|FAILED)$", message = "发送状态只能是PENDING、SENT或FAILED")
        private String sendStatus;

        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime sendTime;
        
        // Getter methods
        public String getTemplateId() {
            return templateId;
        }
        
        public String getEventType() {
            return eventType;
        }
        
        public String getContent() {
            return content;
        }
        
        public String getSendStatus() {
            return sendStatus;
        }
        
        public LocalDateTime getSendTime() {
            return sendTime;
        }
    }

    @Data
    public static class UpdateSendStatusRequest {
        @NotBlank(message = "发送状态不能为空")
        @Pattern(regexp = "^(PENDING|SENT|FAILED)$", message = "发送状态只能是PENDING、SENT或FAILED")
        private String sendStatus;

        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime sendTime = LocalDateTime.now();
        
        // Getter methods
        public String getSendStatus() {
            return sendStatus;
        }
        
        public LocalDateTime getSendTime() {
            return sendTime;
        }
    }
}